package com.onpositive.simple.persistance;

import java.util.EmptyStackException;
import java.util.Stack;

public class RAMNodeStorage extends AbstractNodeStorage {
	
	int container[] ;
	protected Stack<Integer> deletedNodes ;
	
	protected int nodeSize, nodesCount ;
	
	public RAMNodeStorage( int nodeSize ){
		this.nodeSize = nodeSize ;
		container = new int[ 10*nodeSize ] ;
		nodesCount = 0 ;
		deletedNodes = new Stack<Integer>() ;
	}

	@Override
	public AbstractTreeNode getNode( int nodeIndex ) {
		int nodeStart = nodeIndex*nodeSize ;
		return new RAMTreeNode( this, nodeStart, nodeIndex ) ;
	}
	@Override
	public AbstractTreeNode getNewNode() {
		
		int nodeIndex = getVacantNode() ;
		nodesCount++ ;
		int nodeStart = nodeIndex*nodeSize ;
		
		RAMTreeNode treeNode = new RAMTreeNode(this,nodeStart,nodeIndex) ;
		
		for( int i = masterIndex.zeroSubtreeOffset ; i < masterIndex.zeroSubtreeOffset + masterIndex.nodeMaxOrder+1 ; i++ )
			treeNode.setElement(i, masterIndex.emptySubtreeIndicator ) ;
		
		treeNode.setElement( masterIndex.parentNodeOffset, masterIndex.emptySubtreeIndicator) ;
		//treeNode.setElement( masterIndex.sameKeySubtreeRoot, masterIndex.emptySubtreeIndicator) ;
		
		return treeNode ;
	}

	@Override
	public void putNode(AbstractTreeNode node, int nodeIndex) {
//		if ( node instanceof TreeNode )
//		{
//			TreeNode treeNode = (TreeNode)node ;
//
//			int nodeStart = nodeIndex*nodeSize ;
//			for( int i = 0 ; i < nodeSize ; i++ )
//				this.container[ nodeStart + i ] = treeNode.container[i] ;
//		}
	}
	
	private int getVacantNode(){
		
		Integer vacantNode ;
		try{
			vacantNode = deletedNodes.pop() ;
		}
		catch(EmptyStackException e){ 
		
			if ( container.length < (nodesCount+1)*nodeSize )
				reallocateContainer() ;
			
			vacantNode = nodesCount ;
		}
		return vacantNode ;
	}
	
	private void reallocateContainer()
	{
		int tmpContainer[] = new int[ (int)(container.length * 1.4) ] ;
		for( int i = 0 ; i < container.length ; i++  )
			tmpContainer[i] = container[i] ;
		
		container = tmpContainer ;		
	}

	
}
